﻿// Thanks to Rick Strahl for this: System.Web.Mvc
namespace S4sme.Web.Infrastructure.Helpers 
{
    using System.Security.Cryptography;
    using System.Web.Mvc;

    public static class GravatarHelper 
    {
        public static string Gravatar(this HtmlHelper helper, string email, int size) 
        {
            const string Result = "<img src=\"{0}\" alt=\"Gravatar\" class=\"gravatar\" />";
            var url = GetGravatarUrl(email, size);
            return string.Format(Result, url);
        }

        private static string GetGravatarUrl(string email, int size) 
        {
            return string.Format("http://www.gravatar.com/avatar/{0}?s={1}&r=PG", EncryptMd5(email), size);
        }

        /*private static string GetGravatarUrl(string email, int size, string defaultImagePath) 
        {
            return GetGravatarUrl(email, size) + string.Format("&default={0}", defaultImagePath);
        }*/

        private static string EncryptMd5(string value) 
        {
            var md5 = new MD5CryptoServiceProvider();
            var valueArray = System.Text.Encoding.ASCII.GetBytes(value);
            valueArray = md5.ComputeHash(valueArray);
            var encrypted = string.Empty;
            for (var i = 0; i < valueArray.Length; i++)
            {
                encrypted += valueArray[i].ToString("x2").ToLower();
            }

            return encrypted;
        }
    }
}
